package com.imooc.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 获取fastdfs防盗链token
 *
 * @author 顾志杰
 * @date 2021/8/6-8:15
 */
public class FastdfsTokenUtil {

    private static String md5(byte[] source) throws NoSuchAlgorithmException {
        char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(source);
        byte[] tmp = md.digest();
        char[] str = new char[32];
        int k = 0;

        for(int i = 0; i < 16; ++i) {
            str[k++] = hexDigits[tmp[i] >>> 4 & 15];
            str[k++] = hexDigits[tmp[i] & 15];
        }

        return new String(str);
    }


    public static String getToken(String remote_filename, int ts, String secret_key) throws  Exception {
        byte[] bsFilename = remote_filename.getBytes(StandardCharsets.UTF_8);
        byte[] bsKey = secret_key.getBytes(StandardCharsets.UTF_8);
        byte[] bsTimestamp = (new Integer(ts)).toString().getBytes(StandardCharsets.UTF_8);
        byte[] buff = new byte[bsFilename.length + bsKey.length + bsTimestamp.length];
        System.arraycopy(bsFilename, 0, buff, 0, bsFilename.length);
        System.arraycopy(bsKey, 0, buff, bsFilename.length, bsKey.length);
        System.arraycopy(bsTimestamp, 0, buff, bsFilename.length + bsKey.length, bsTimestamp.length);
        return md5(buff);
    }


    public static String getToken() throws Exception{

        Date date = new Date(2147082833);

        int ts = (int) (System.currentTimeMillis() / 1000 );
        // 写死一个时间 1970年3月的 不会过期   不提倡使用
//        int ts = 2147082833;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String res = simpleDateFormat.format(date);
        String remoteFilename = "M00/00/26/CgEIJGEfQH2AUuS_AB4B23Sr8Mo596.jpg";
        System.out.println("lts="+ts);
        String token = getToken(remoteFilename, ts, "2603a17d-1d78-4e8d-81df-b1bfa064f7ce");
        System.out.println("token="+token);
        System.out.println("http://116.182.13.185:9091/group1/"+remoteFilename+"?token="+token+"&ts="+ts);
        return "http://116.182.13.185:9091/group1/"+remoteFilename+"?token="+token+"&ts="+ts;
    }

    public static void main(String[] args) {
        try {
            getToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
